package com.bootdo.imgtext.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.common.utils.ExcelUtils;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.imgtext.dao.DocitemDao;
import com.bootdo.imgtext.domain.DocfileDO;
import com.bootdo.imgtext.domain.DocitemDO;
import com.bootdo.imgtext.service.DocfileService;

/**
 * 图文检测
 * 
 * @author ke
 * @email 1992lcg@163.com
 * @date 2018-08-07 14:27:42
 */

@Controller
@RequestMapping("/imgtext/docfile")
public class DocfileController {
	@Autowired
	private DocfileService docfileService;

	@Autowired
	private DocitemDao docitemDao;

	@Value("${excelFile}")
	private String filePath;

	@GetMapping()
	@RequiresPermissions("imgtext:docfile:docfile")
	String Docfile() {
		return "imgtext/docfile/docfile";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("imgtext:docfile:docfile")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<DocfileDO> docfileList = docfileService.list(query);
		int total = docfileService.count(query);
		PageUtils pageUtils = new PageUtils(docfileList, total);
		return pageUtils;
	}

	@GetMapping("/add")
	@RequiresPermissions("imgtext:docfile:add")
	String add() {
		return "imgtext/docfile/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("imgtext:docfile:edit")
	String edit(@PathVariable("id") Integer id, Model model) {
		DocfileDO docfile = docfileService.get(id);
		model.addAttribute("docfile", docfile);
		return "imgtext/docfile/edit";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("imgtext:docfile:add")
	public R save(@RequestParam("file") MultipartFile file) {

		String filename = file.getOriginalFilename();
		try {
			FileUtil.uploadFile(file.getBytes(), filePath, filename);
		} catch (Exception e) {
			return R.error();
		}
		Map<String, List<List<String>>> excelContent = ExcelUtils.read(filePath + filename);
		for (Map.Entry<String, List<List<String>>> sheetContent : excelContent.entrySet()) {
			String sheetName = sheetContent.getKey();
			DocfileDO docfileDO = new DocfileDO();
			docfileDO.setFilename(filename);
			docfileDO.setSheetname(sheetName);
			docfileDO.setStatus("上传成功");
			docfileDO.setAcceptanceNum(0);
			docfileDO.setDocNum(sheetContent.getValue().size());
			docfileDO.setFailNum(0);

			docfileService.save(docfileDO);
			int fileId = docfileDO.getId();
			docfileService.saveAndCheck(fileId, sheetContent.getValue());
		}
		return R.ok();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("imgtext:docfile:edit")
	public R update(DocfileDO docfile) {
		docfileService.update(docfile);
		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("imgtext:docfile:remove")
	public R remove(Integer id) {
		if (docfileService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("imgtext:docfile:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids) {
		docfileService.batchRemove(ids);
		return R.ok();
	}

	/**
	 * 下载模板
	 */
	@GetMapping("/downloadTemplete")
	public void downloadTemplete(HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding(request.getCharacterEncoding());
		response.setContentType("application/octet-stream");
		InputStream fis = this.getClass().getResourceAsStream("/detection/图文模板.xls");
		try {
			response.setHeader("Content-Disposition",
					"attachment; filename=" + URLEncoder.encode("图文模板", "utf8") + ".xls");
			IOUtils.copy(fis, response.getOutputStream());
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@GetMapping("/downloadResult")
	public void downloadResult(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		DocfileDO docfileDO = docfileService.get(Integer.parseInt(id));
		if (docfileDO == null) {
			return;
		}

		Map<String, Object> map = new HashMap<>();
		map.put("sort", "sn");
		map.put("order", "asc");
		map.put("fileId", docfileDO.getId());
		List<DocitemDO> items = docitemDao.list(map);

		response.setCharacterEncoding(request.getCharacterEncoding());
		response.setContentType("application/msexcel");

		try (HSSFWorkbook workbook = new HSSFWorkbook(); OutputStream os = response.getOutputStream();) {
			response.setHeader("Content-Disposition",
					"attachment; filename=" + URLEncoder.encode("检测结果_" + docfileDO.getFilename(), "utf8"));
			HSSFSheet sheet = workbook.createSheet(docfileDO.getSheetname());

			sheet.setColumnWidth(2, 10000);
			sheet.setColumnWidth(3, 14000);
			sheet.setColumnWidth(6, 10000);

			int rowIndex = 0;// 标识位，用于标识sheet的行号
			// 遍历数据集，将其写入excel中
			// 写表头数据
			HSSFRow titleRow = sheet.createRow(rowIndex++);
			// 创建表头单元格,填值
			titleRow.createCell(0).setCellValue("序号");
			titleRow.createCell(1).setCellValue("日期");
			titleRow.createCell(2).setCellValue("标题");
			titleRow.createCell(3).setCellValue("链接");
			titleRow.createCell(4).setCellValue("浏览量");
			titleRow.createCell(5).setCellValue("原创/汇聚");
			titleRow.createCell(6).setCellValue("检测结果");
			titleRow.createCell(7).setCellValue("合格");

			// 循环写入主表数据
			for (DocitemDO item : items) {
				HSSFRow row = sheet.createRow(rowIndex++);
				row.createCell(0).setCellValue(item.getSn());
				row.createCell(1).setCellValue(item.getDocDate());
				row.createCell(2).setCellValue(item.getTitle());
				row.createCell(3).setCellValue(item.getUrl());
				row.createCell(4).setCellValue(item.getViews());
				row.createCell(5).setCellValue(item.getItemComments());
				row.createCell(6).setCellValue(item.getCheckResult());
				String hege = "是";
				if (item.getCheckResult().contains("无logo图片;") || item.getCheckResult().contains("无作者")
						|| item.getCheckResult().contains("暂不支持该网站") || item.getCheckResult().contains("Exception")
						|| item.getCheckResult().contains("Error")) {
					hege = "否";
					HSSFCellStyle style = workbook.createCellStyle();
					style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
					style.setFillForegroundColor(HSSFColorPredefined.RED.getIndex());
					row.setRowStyle(style);
				}
				row.createCell(7).setCellValue(hege);

			}
			workbook.write(os);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
